<template>
  <div class="search-suggestion-container">
    <!-- <div v-html="htmlStr"></div> -->
    <van-cell 
      v-for="(suggestion, index) in suggestionsList"
      icon="search"
      @click="suggestionClick(suggestion)"
    >
      <div slot="title" v-html="highLight(suggestion)">
      </div>
    </van-cell>
  </div>
</template>

<script>
import {getSuggestionListApi} from '@/api/search';
import {debounce} from 'lodash';

// import _ from 'lodash';
// 函数防抖
/* 
const fn = _.debounce(function (param) {
  console.log("防抖hello",param);
},1000)
fn(1);
fn(2);
fn(3);
//=> 防抖hello 3
*/

/* 
const fn = _.debounce(function (param) {
  console.log("防抖hello",param);
},1000);

fn(1);

setTimeout(() => {
  fn('900ms的调用')
}, 900);

setTimeout(() => {
  fn('1200ms的调用')
}, 1200);
//=> 防抖hello 1200ms的调用 
*/

export default {
  name: "SearchSuggestion",
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestionsList:[],
      // htmlStr: '<span style="color: red">hello</span>world'
    };
  },
  computed: {},
  watch: {
    // 属性名：要监视的数据的名称
    // searchText() {
    //   console.log("监视数据");
    // }

    // searchText: {
    //   handler: debounce(async function () {
    //     const q = this.searchText
    //     if (!q) {
    //       return
    //     }
    //     const { data } = await getSuggestions(q)
    //     this.suggestions = data.data.options
    //   }, 200),
    //   immediate: true
    // },

    searchText: {
      // 当数据发生变化时，则会执行handler 处理函数
      handler: debounce(async function(){
        const {data} = await getSuggestionListApi(this.searchText);
        this.suggestionsList = data.data.options;
      },250),

      // async handler() { 
      //   const {data} = await getSuggestionListApi(this.searchText);
      //   this.suggestionsList = data.data.options;
      //   console.log("监视数据中",data);
      //   // 找到数据接口
      //   // 请求数据接口
      //   // 模板绑定展示
      // },
      //该回调将会在侦听开始之后被立即调用
      immediate: true   
    }
  },
  methods: {
    // 高亮显示
    highLight(str) {
      //a、/a/gi  
      // 正则表达式 /中间的内容/都会当做正则匹配模式字符来对待
      // /this.searchText/gi 错误的写法
      // RegExp是正则表达式的构造函数
      // 参数1：字符串  
      // 参数2：匹配模式
      // 返回值：正则对象
      const reg = new RegExp(this.searchText,'gi');
      const highLightStr = str.replace(reg,`<span style="color: red">${this.searchText}</span>`);
      return highLightStr;
    },
    // 点击了cell
    suggestionClick(suggestionStr) {
      this.$emit("changeSearchText",suggestionStr);
    }
  },
  created() {},
  mounted() {

  },
};
</script>

<style lang='less' scoped>
//@import url(); 引入公共css类
</style>